// Copyright 2025 CCC
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
function typeOf(obj: Record<string, any>) {
  const toString = Object.prototype.toString;
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regexp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object FormData]': 'formData',
  } as Record<string, any>;

  return map[toString.call(obj)];
}

/**
 *
 * @param {Array} obj 被拷贝对象
 * @returns
 */
const deepClone = (obj: any) => {
  if (obj === null) {
    return null;
  }

  const clone = Object.assign({}, obj);
  Object.keys(clone).forEach(
    (key) => (clone[key] = typeOf(obj[key]) === 'object' ? deepClone(obj[key]) : obj[key]),
  );

  if (Array.isArray(obj)) {
    clone.length = obj.length;

    return Array.from(clone);
  }

  return clone;
};

export { deepClone };
